package com.taskmanagement.controller;

import com.taskmanagement.mapper.TaskMapper;
import com.taskmanagement.entity.Task;
import com.taskmanagement.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.*;

@RestController
@RequestMapping("/api/tasks")
public class TaskController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private TaskMapper taskMapper;

    // 🆕 添加统计接口
    @GetMapping("/stats")
    public ResponseEntity<?> getTaskStats() {
        try {
            BigInteger userId = getCurrentUserId();
            // 获取用户的所有任务
            List<Task> tasks = taskMapper.findByUserIdWithStepCounts(userId);

            // 计算统计数据
            int total = tasks.size();
            int completed = 0;
            int pending = 0;
            int inProgress = 0;

            for (Task task : tasks) {
                switch (task.getStatus()) {
                    case "completed":
                        completed++;
                        break;
                    case "pending":
                        pending++;
                        break;
                    case "in_progress":
                        inProgress++;
                        break;
                }
            }

            Map<String, Object> stats = new HashMap<>();
            stats.put("total", total);
            stats.put("completed", completed);
            stats.put("pending", pending);
            stats.put("inProgress", inProgress);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", stats);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取统计数据失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 🆕 添加获取当前用户任务接口
    @GetMapping("/my-tasks")
    public ResponseEntity<?> getCurrentUserTasks(@RequestParam Map<String, String> params) {
        try {
            BigInteger userId = getCurrentUserId();

            // 处理可能的过滤参数
            String status = params.getOrDefault("status", null);
            String sortBy = params.getOrDefault("sortBy", "createdAt");
            String sortOrder = params.getOrDefault("sortOrder", "desc");

            // 获取用户的任务，可以根据参数进行过滤
            List<Task> tasks;
            if (status != null && !status.isEmpty()) {
                tasks = taskMapper.findByUserIdAndStatusWithStepCounts(userId, status);
            } else {
                tasks = taskMapper.findByUserIdWithStepCounts(userId);
            }

            // 根据参数进行排序
            sortTasks(tasks, sortBy, sortOrder);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", tasks);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取当前用户任务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 添加任务排序辅助方法
    private void sortTasks(List<Task> tasks, String sortBy, String sortOrder) {
        Comparator<Task> comparator;

        switch (sortBy) {
            case "title":
                comparator = Comparator.comparing(Task::getTitle, Comparator.nullsLast(String::compareTo));
                break;
            case "priority":
                comparator = Comparator.comparing(Task::getPriority, Comparator.nullsLast(Integer::compareTo));
                break;
            case "status":
                comparator = Comparator.comparing(Task::getStatus, Comparator.nullsLast(String::compareTo));
                break;
            default: // 默认按创建时间排序
                comparator = Comparator.comparing(Task::getCreatedAt, Comparator.nullsLast(Date::compareTo));
        }

        // 如果是降序，反转比较器
        if ("desc".equalsIgnoreCase(sortOrder)) {
            comparator = comparator.reversed();
        }

        tasks.sort(comparator);
    }

    @GetMapping
    public ResponseEntity<?> getAllTasks() {
        try {
            BigInteger userId = getCurrentUserId();
            // 使用新的 Mapper 方法
            List<Task> tasks = taskMapper.findByUserIdWithStepCounts(userId);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", tasks);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getTaskById(@PathVariable BigInteger id) {
        try {
            BigInteger userId = getCurrentUserId();
            // 使用新的 Mapper 方法
            Task task = taskMapper.findByIdAndUserIdWithStepCounts(id, userId);

            if (task == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "任务不存在");
                return ResponseEntity.status(404).body(response);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", task);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping
    public ResponseEntity<?> createTask(@RequestBody Task task) {
        try {
            BigInteger userId = getCurrentUserId();
            task.setUserId(userId);

            Task createdTask = taskService.createTask(task);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "任务创建成功");
            response.put("data", createdTask);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateTask(@PathVariable BigInteger id, @RequestBody Task task) {
        try {
            BigInteger userId = getCurrentUserId();
            Task existingTask = taskService.findByIdAndUserId(id, userId);

            if (existingTask == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "任务不存在");
                return ResponseEntity.badRequest().body(response);
            }

            task.setId(id);
            task.setUserId(userId);

            Task updatedTask = taskService.updateTask(task);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "任务更新成功");
            response.put("data", updatedTask);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteTask(@PathVariable BigInteger id) {
        try {
            BigInteger userId = getCurrentUserId();
            boolean deleted = taskService.deleteTask(id, userId);

            if (!deleted) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "任务不存在或删除失败");
                return ResponseEntity.badRequest().body(response);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "任务删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PatchMapping("/{id}/status")
    public ResponseEntity<?> updateTaskStatus(@PathVariable BigInteger id, @RequestBody Map<String, String> statusRequest) {
        try {
            BigInteger userId = getCurrentUserId();
            String status = statusRequest.get("status");

            boolean updated = taskService.updateTaskStatus(id, userId, status);

            if (!updated) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "任务不存在或状态更新失败");
                return ResponseEntity.badRequest().body(response);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "任务状态更新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 在 TaskController 类中添加这个方法
    @RequestMapping(value = "/**", method = RequestMethod.OPTIONS)
    public ResponseEntity<?> handleOptions() {
        return ResponseEntity.ok().build();
    }

    private BigInteger getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String username = userDetails.getUsername();
        return taskService.findByUsername(username).getId();
    }


}
